module StateLibrary
  require 'cgi'
  require 'fileutils'
  include FileUtils

  def download_page(multi_issue, channel_id, subchannel, marc_id, some_path, issue_id, page_number, output_file)
    base_url = "http://res4.nlc.gov.cn"
    top_flag = multi_issue ? "" : "t"
    filename_size = multi_issue ? "&filenameSize=3" : ""
    
    pdf_read_url = "#{base_url}/home/pdfRead.trs?"
    pdf_read_url << "marcid=#{marc_id}&channelid=#{channel_id}&bookid=#{issue_id}&dataid=civination&currentpage=#{page_number}"
    pdf_read_url << "&pathinfo=#{some_path}&top=#{top_flag}&haveTop=false&type=new&subchannel=#{subchannel}"
    pdf_read_url << "&ifPdfReader=1&jumpType=0#{filename_size}"
    # puts pdf_read_url
    
    pdf_read_html = "pdfRead.html"
    download pdf_read_url, pdf_read_html
    
    # /home/pdfShow.trs?currentfilename=dDAwMDAyXzAwLnBkZg==&currentpage=2&urlsize=null&url=L21udC9kaXNrM18zL3ppcG1pbmd1b3R1c2h1My8xNzMvMDdqaDAxMDY4NF8wMDEuemlw&pathinfo=749_200&subchannel=1&dataid=civination&bookid=MDdqaDAxMDY4NF8wMDE=&id=MDdqaDAxMDY4NA==&channelid=281&top=t&end=.pdf
    pdf_show_path = File.open(pdf_read_html){|f| f.read}.match(/^.+\/(home\/pdfShow.trs\?.+end=.pdf)/i)[1]
    pdf_url = "#{base_url}/#{pdf_show_path}"
    # puts pdf_url
    
    download pdf_url, output_file
    puts "Page #{page_number} of #{issue_id} has been downloaded"
  end

  def download_publication(name, channel_id, subchannel, marc_id, some_path, book_id_format, issue_count, max_page)
    multi_issue = (issue_count > 1)
    
    (1..issue_count).each do |issue|
      issue_id = sprintf(book_id_format, issue)
      output_dir = "pdf/#{issue_id}-#{name}"
      mkdir_p output_dir

      (1..max_page).each do |page|
        begin 
          output_file = "#{output_dir}/#{sprintf('%04d', page)}.pdf"
          if File.exist?(output_file)
            puts "Page #{page} of #{issue_id} has been ignored"
            next
          end
          download_page multi_issue, channel_id, subchannel, marc_id, some_path, issue_id, page, output_file
        rescue Exception => e
          puts e
          puts "!!! Page #{page} of #{issue_id} cannot be found"
          break
        end
      end
    end
  end
  
  private
  def download(url, output)
    system "wget -o wget.log -O #{output} \"#{url}\""
  end
end
